"""随机 User-Agent 管理器
提供随机 User-Agent 和协同头部的生成与管理功能
"""

import random
import time
from typing import Dict, Tuple
from datetime import datetime, timedelta
from .logger import get_monitor_logger

monitor_logger = get_monitor_logger()


class UserAgentManager:
    """User-Agent 管理器 - 单例模式
    
    负责生成随机 User-Agent 和协同头部，并定期更换
    """
    
    _instance = None
    _initialized = False
    
    def __new__(cls, *args, **kwargs):
        """单例模式：确保每个进程只创建一个实例"""
        if cls._instance is None:
            cls._instance = super(UserAgentManager, cls).__new__(cls)
        return cls._instance
    
    def __init__(self, refresh_interval_hours: Tuple[int, int] = (3, 6)):
        """
        初始化 User-Agent 管理器
        
        Args:
            refresh_interval_hours: 刷新间隔小时数范围 (最小, 最大)
        """
        # 防止重复初始化
        if self._initialized:
            return
        
        self.refresh_interval_hours = refresh_interval_hours
        self.current_ua_data = None
        self.next_refresh_time = None
        
        # 预定义的 User-Agent 列表
        self.user_agents = [
            # Chrome Windows
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            
            # Chrome macOS
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
            
            # Firefox Windows
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:119.0) Gecko/20100101 Firefox/119.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:118.0) Gecko/20100101 Firefox/118.0',
            
            # Safari macOS
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15',
            
            # Edge Windows
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
        ]
        
        # 生成初始 UA 数据
        self._generate_new_ua_data()
        
        # 标记已初始化
        UserAgentManager._initialized = True
    
    def _generate_new_ua_data(self) -> None:
        """生成新的 User-Agent 数据和协同头部"""
        user_agent = random.choice(self.user_agents)
        
        # 根据 User-Agent 生成协同头部
        headers = self._generate_coordinated_headers(user_agent)
        
        # 计算下次刷新时间
        refresh_hours = random.uniform(*self.refresh_interval_hours)
        next_refresh = datetime.now() + timedelta(hours=refresh_hours)
        
        self.current_ua_data = {
            'user_agent': user_agent,
            'headers': headers,
            'created_at': datetime.now(),
            'refresh_hours': refresh_hours
        }
        self.next_refresh_time = next_refresh
        
        import os
        pid = os.getpid()
        monitor_logger.info(f"🔄 生成新的 User-Agent [PID:{pid}]: {user_agent[:50]}... (下次刷新: {refresh_hours:.1f}小时后)")
    
    def _generate_coordinated_headers(self, user_agent: str) -> Dict[str, str]:
        """根据 User-Agent 生成协同的请求头部"""
        headers = {
            'User-Agent': user_agent,
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'ja',
            'Origin': 'https://jp.mercari.com',
            'Referer': 'https://jp.mercari.com/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'cross-site',
            'X-Country-Code': 'KR',
            'X-Platform': 'web',
            'priority': 'u=1, i'
        }
        
        # 根据浏览器类型调整 Sec-Ch-Ua 头部
        if 'Chrome' in user_agent:
            # 提取 Chrome 版本号
            import re
            chrome_match = re.search(r'Chrome/([\d.]+)', user_agent)
            if chrome_match:
                chrome_version = chrome_match.group(1).split('.')[0]
                headers.update({
                    'Sec-Ch-Ua': f'"Not)A;Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"',
                    'Sec-Ch-Ua-Mobile': '?0',
                    'Sec-Ch-Ua-Platform': '"Windows"' if 'Windows' in user_agent else '"macOS"'
                })
        elif 'Firefox' in user_agent:
            # Firefox 不使用 Sec-Ch-Ua 头部
            pass
        elif 'Safari' in user_agent and 'Chrome' not in user_agent:
            # Safari 的特殊处理
            headers.update({
                'Sec-Ch-Ua-Mobile': '?0',
                'Sec-Ch-Ua-Platform': '"macOS"'
            })
        elif 'Edg' in user_agent:
            # Edge 浏览器
            import re
            edge_match = re.search(r'Edg/([\d.]+)', user_agent)
            if edge_match:
                edge_version = edge_match.group(1).split('.')[0]
                headers.update({
                    'Sec-Ch-Ua': f'"Not)A;Brand";v="8", "Chromium";v="{edge_version}", "Microsoft Edge";v="{edge_version}"',
                    'Sec-Ch-Ua-Mobile': '?0',
                    'Sec-Ch-Ua-Platform': '"Windows"'
                })
        
        return headers
    
    def get_current_ua_data(self) -> Dict[str, any]:
        """获取当前的 User-Agent 数据
        
        Returns:
            包含 user_agent 和 headers 的字典
        """
        # 检查是否需要刷新
        if self.should_refresh():
            self._generate_new_ua_data()
        
        return self.current_ua_data
    
    def should_refresh(self) -> bool:
        """检查是否应该刷新 User-Agent"""
        if self.next_refresh_time is None:
            return True
        return datetime.now() >= self.next_refresh_time
    
    def force_refresh(self) -> None:
        """强制刷新 User-Agent"""
        monitor_logger.info("🔄 强制刷新 User-Agent")
        self._generate_new_ua_data()
    
    def get_time_until_next_refresh(self) -> float:
        """获取距离下次刷新的时间（小时）"""
        if self.next_refresh_time is None:
            return 0
        
        delta = self.next_refresh_time - datetime.now()
        return max(0, delta.total_seconds() / 3600)
    
    def get_status(self) -> Dict[str, any]:
        """获取管理器状态信息"""
        if self.current_ua_data is None:
            return {'status': 'not_initialized'}
        
        return {
            'status': 'active',
            'current_user_agent': self.current_ua_data['user_agent'][:50] + '...',
            'created_at': self.current_ua_data['created_at'].isoformat(),
            'refresh_hours': self.current_ua_data['refresh_hours'],
            'next_refresh_time': self.next_refresh_time.isoformat() if self.next_refresh_time else None,
            'hours_until_refresh': self.get_time_until_next_refresh(),
            'should_refresh': self.should_refresh()
        }


# 创建全局实例
default_ua_manager = UserAgentManager()